package com.example.basic.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.alibaba.fastjson.JSONObject;
import com.example.basic.controller.dto.SoLineImportDTO;
import com.example.basic.listener.ReadListener;
import com.example.basic.service.ExcelService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class ExcelServiceImpl implements ExcelService {

    @Override
    public List<SoLineImportDTO> readDataList(MultipartFile file) {
        ExcelReader excelReader = null;
        List<SoLineImportDTO> dataList;
        try {
            excelReader = EasyExcel.read(file.getInputStream()).headRowNumber(1).build();
            ReadListener<SoLineImportDTO> readListener = new ReadListener<>();
            ReadSheet readSheet = EasyExcel.readSheet(0)
                    .head(SoLineImportDTO.class)
                    .registerReadListener(readListener).build();
            excelReader.read(readSheet);
            dataList = readListener.getDataList();
//            String jsonString = JSONObject.toJSON(readListener.getDataList()).toString();
//            dataList = JSONObject.parseArray(jsonString, SoLineImportDTO.class);
        } catch (IOException e) {
            throw new RuntimeException("Import IOException!");
        } finally {
            if (null != excelReader) {
                excelReader.finish();
            }
        }
        return dataList;
    }
}
